package com.eqs.enterprisequestionnaire.service.Impl;

import com.eqs.enterprisequestionnaire.model.pojo.Answer;
import com.eqs.enterprisequestionnaire.model.pojo.Option;
import com.eqs.enterprisequestionnaire.model.pojo.Question;
import com.eqs.enterprisequestionnaire.service.HistoryService;
import com.eqs.enterprisequestionnaire.service.LevelQuestionAnalysisService;
import com.eqs.enterprisequestionnaire.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.isLevelType;

@Service
public class LevelQuestionAnalysisImpl implements LevelQuestionAnalysisService {
    @Autowired
    private QuestionService questionService;

    @Autowired
    private HistoryService historyService;
    public Double getAverageScore(Integer questionId){
        Question question = questionService.selectByQuestionId(questionId);
        if (!isLevelType(question.getType())) {
            return null;
        }

        // 获取该问题的所有答案
        List<Answer> answers = historyService.getListAnswerByQuestionId(questionId);

        int countAnswer = answers.size();
        int totalScore = 0;
        for (Answer answer : answers) {
            totalScore += Integer.parseInt(answer.getText());
        }

        if (countAnswer == 0) {
            return 0.0;
        }
        return (double) totalScore/countAnswer;
    }
    public Map<Integer,Double> getLevelRankingProportions(Integer questionId){
        Question question = questionService.selectByQuestionId(questionId);
        if (!isLevelType(question.getType())) {
            return null;
        }
        // 获取该问题的所有答案
        List<Answer> answers = historyService.getListAnswerByQuestionId(questionId);

        // 初始化每个 level 的计数器
        Map<Integer, Integer> levelCounts = new HashMap<>();
        for (int i = 1; i <= 5; i++) {
            levelCounts.put(i, 0);
        }

        // 统计每个 level 的出现次数
        for (Answer answer : answers) {
            int level = Integer.parseInt(answer.getText());
            levelCounts.put(level, levelCounts.get(level) + 1);
        }

        // 计算每个 level 的比例
        Map<Integer, Double> levelProportions = new HashMap<>();
        int totalAnswers = answers.size();
        for (int i = 1; i <= 5; i++) {
            int count = levelCounts.get(i);
            double proportion = totalAnswers == 0 ? 0.0 : (double) count / totalAnswers;
            levelProportions.put(i, proportion);
        }

        return levelProportions;
    }

}
